# Filters added to this controller apply to all controllers in the application.
# Likewise, all the methods added will be available for all controllers.

class ApplicationController < ActionController::Base
  
  # The before filters for all controllers
  before_filter :get_user
  
  # Around filter
  #around_filter :catch_exceptions
  
  # Includes all the helpers from application_helper.rb
  helper :all
  
  protect_from_forgery # :secret => 'e1852b6a3dfa0d60a884dfedd73a7a29'
  
  #
  # Authenticates the user
  #
  def authenticate
    # We use different auth mechanisms depending on whether we're using XML or HTML
    use_session_auth = true
    respond_to do |format|
      format.html {
        use_session_auth = true 
      }
      format.xml { 
        use_session_auth = false 
      }
    end
    # Session based auth or not
    if use_session_auth
      if session[:user_id] 
        # Found a session, auth successful
        return true
      else
        # Check for cookie auth
        if cookies[:auth_token]
          user = User.find_by_remember_token(cookies[:auth_token]) 
          if user && !user.remember_token_expires.nil? && Time.now < user.remember_token_expires 
            # Found a valid cookie, auth successful
            session[:user_id] = user
            return true
          end
        end
        # Redirect to login page
        session[:return_to] = request.request_uri
        redirect_to :controller => "logins"
        return false
      end
    else
      return true
    end
  end
    
  #
  # Administrator
  #
  def ensure_administrator
    if session[:user_id] 
      get_user
      unless @user.is_administrator
        logger.info "User is not an administrator"
        redirect_to :controller => "logins"
      end
    else
      logger.info "Can not find a user session"
      redirect_to :controller => "logins"
    end 
  end    
  
  #
  #
  #
  def catch_exceptions   
  end
  
  # 
  # Do we have a user logged in
  #
  def logged_in?
    if session[:user_id]
      return true
    else
      return false
    end
  end

  #
  # Sets a user variable
  #
  def get_user
    begin
      @user = User.find(session[:user_id]) if session[:user_id]
    rescue
      session[:user_id] = nil
      logger.info "Couldn't find user for session"
    end
  end
  
  #
  # Sets a user session and cookies as well as their login time and IP
  #
  def set_user(user)
    user.last_login_at = Time.now.utc
    user.last_login_ip = request.remote_ip
    
    session[:user_id] = user.id
    
    if params[:remember_me]
      logger.info("Remembering user with cookie")
      require 'digest/sha1'
      user.remember_token_expires = 4.weeks.from_now
      user.remember_token = Digest::SHA1.hexdigest("#{rand(9999)}--#{user.email}--#{user.remember_token_expires}")
 
      cookies[:auth_token] = { :value => user.remember_token , 
                               :expires => user.remember_token_expires 
                             }     
    end
    user.save
  end
    
  #
  # Logging
  #
  def log_event(comment, logged_id = nil, detail = nil)   
    log = Log.new({
        :action => params[:action],
        :controller => params[:controller],
        :remote_ip => request.remote_ip,
        :comment => comment,
        :logged_id => logged_id,
        :detail => detail
      })   
    log.save   
  end 
end
